package com.dao;

import com.entity.Blog;
import com.util.PageUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author hyl
 * @Date 2022/6/25 10:01
 **/
public class BlogDaoImpl extends BaseDao implements BlogDao {
	@Override
	public List<Blog> findByPage(Integer beginIndex, Integer showSize) {
		Connection conn = getConnection();
		String sql = "Select * from blog limit ?,?";
		PreparedStatement pstm  = null;
		ResultSet rs = null;
		try {
			pstm = conn.prepareStatement(sql);
			pstm.setInt(1, beginIndex);
			pstm.setInt(2, showSize);
			rs =  pstm.executeQuery();
			List<Blog> list = new ArrayList<Blog>();
			while(rs.next()){
				Blog blog = new Blog(rs.getInt("id"),
						rs.getInt("uid"),
						rs.getString("content"),
						rs.getString("images"),
						rs.getString("time"),
						rs.getInt("state"),
						rs.getInt("fromBid"));
				list.add(blog); //将从数据库中获取的数据，循环添加到==》集合
			}
			return list;
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}

		closeAll(rs, pstm, conn);
		return null;
	}

	@Override
	public List<Blog> findByPage(PageUtil pageUtil) {
		Connection conn = getConnection();
		String sql = "Select * from blog limit ?,?";
		PreparedStatement pstm  = null;
		ResultSet rs = null;
		try {
			pstm = conn.prepareStatement(sql);
			pstm.setInt(1, pageUtil.getBeginIndex());
			pstm.setInt(2, pageUtil.getShowSize());
			rs =  pstm.executeQuery();
			List<Blog> list = new ArrayList<Blog>();
			while(rs.next()){
				Blog blog = new Blog(rs.getInt("id"),
						rs.getInt("uid"),
						rs.getString("content"),
						rs.getString("images"),
						rs.getString("time"),
						rs.getInt("state"),
						rs.getInt("fromBid"));
				list.add(blog); //将从数据库中获取的数据，循环添加到==》集合
			}
			return list;
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}

		closeAll(rs, pstm, conn);
		return null;
	}

	@Override
	public int findPageCount() {
		Connection conn = getConnection();
		String sql = "Select count(1) cnt from blog";
		PreparedStatement pstm  = null;
		ResultSet rs = null;
		try {
			pstm = conn.prepareStatement(sql);
			rs =  pstm.executeQuery();
			int ret = 0;
			while(rs.next()){
				ret = rs.getInt("cnt");
			}
			return ret;
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}

		closeAll(rs, pstm, conn);
		return 0;
	}
}
